package com.ljb.downloadmanager;

import android.app.DownloadManager;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import java.io.File;

/**
 * Created by lijianbin on 2017/1/20.
 */
public class DMHelper {
    public static final String TAG = "DMHelper";
    public static Context c;
    public static  File saveFile = new File(Environment.getExternalStorageDirectory(), "shukuang.apk");

    /**
     * @param context 为了防止内存泄漏,请使用全局上下文
     */
    public DMHelper(Context context) {
        c = context;
    }

    /**
     * 下载
     *
     * @param downloadUrl
     */
    public void download(String downloadUrl, DMHelperListener listener) {
        dmListener = listener;
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl));
        request.setTitle("数矿");
        request.setDescription("描述信息");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        // 设置下载文件的保存位置
        request.setDestinationUri(Uri.fromFile(saveFile));
        DownloadManager manager = (DownloadManager) c.getSystemService(Context.DOWNLOAD_SERVICE);
        long downloadId = manager.enqueue(request);
        // manager.remove(downloadId);
    }

    /**
     * @param downloadId 根据Id查询下载状态
     */
    public static void query(long downloadId) {
//        获取下载管理器服务的实例
        DownloadManager manager = (DownloadManager) c.getSystemService(Context.DOWNLOAD_SERVICE);
//        创建一个查询对象
        DownloadManager.Query query = new DownloadManager.Query();
//        根据 下载ID 过滤结果
        query.setFilterById(downloadId);
//        还可以根据状态过滤结果
//        query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
//        执行查询, 返回一个 Cursor(相当于查询数据库)
        Cursor cursor = manager.query(query);
        if (!cursor.moveToFirst()) {
            cursor.close();
            if (dmListener != null)
                dmListener.doError();
            Log.e(TAG, "query: 下载失败 ");
            return;
        }
//        下载ID
        long id = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID));
//        下载请求的状态
        int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
//        下载文件在本地保存的路径
        String localFilename = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
//        已下载的字节大小
        long downloadedSoFar = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
//        下载文件的总字节大小
        long totalSize = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
        cursor.close();
        Log.e(TAG, "query: 下载进度: " + downloadedSoFar + "/" + totalSize);
        /**
         * 判断是否下载成功，其中状态 status 的值有 5 种:
         *     DownloadManager.STATUS_SUCCESSFUL:   下载成功
         *     DownloadManager.STATUS_FAILED:       下载失败
         *     DownloadManager.STATUS_PENDING:      等待下载
         *     DownloadManager.STATUS_RUNNING:      正在下载
         *     DownloadManager.STATUS_PAUSED:       下载暂停
         */
        if (status == DownloadManager.STATUS_SUCCESSFUL) {
            /**
             * 特别注意: 查询获取到的 localFilename 才是下载文件真正的保存路径，在创建
             * 请求时设置的保存路径不一定是最终的保存路径，因为当设置的路径已是存在的文件时，
             * 下载器会自动重命名保存路径，例如: .../demo-1.apk, .../demo-2.apk
             */
            Log.e(TAG, "query: 下载成功, 打开文件, 文件路径: " + localFilename);
            if (dmListener != null)
                dmListener.doSuccess();
            return;
        }
        if (dmListener != null)
            dmListener.doError();
        Log.e(TAG, "query: 下载失败");
        return;
    }

    private static DMHelperListener dmListener;

    public interface DMHelperListener {
        void doSuccess();

        void doError();
    }

}
